/**
 * 自定义FullScreenLoading
 */
const FullScreenLoading = {
  show: false,
  component: null
}

import Loading from './Loading'

export default {
  install (Vue) {
    Vue.prototype.$fullScreenLoading = function (text = '正在加载中...', type) {
      if (type === 'close') {
        FullScreenLoading.component.show = FullScreenLoading.show = false;
      } else {
        if (FullScreenLoading.show) {
          return
        }
        /**
         * Vue构造器，创建一个“子类”，参数是一个包含组件选项的对象，其中,data选项中必须是函数
         * Vue.extend通常和Vue.extend + $mount()
         */
        let FullScreenLoadingComponent = Vue.extend({
          data: function () {
            return {
              show: FullScreenLoading.show
            }
          },
          template: `<div class="fullScreenLoading-container" v-show="show"><div  class="fullScreenLoading">${text}</div></div>`
        })
        FullScreenLoading.component = new FullScreenLoadingComponent()
        let element = FullScreenLoading.component.$mount().$el
        document.body.appendChild(element)
        FullScreenLoading.component.show = FullScreenLoading.show = true
      }
    };
    // 添加实例方法
    ['open', 'close'].forEach(type => {
      Vue.prototype.$fullScreenLoading[type] = (text) => Vue.prototype.$fullScreenLoading(text, type);
    });

    const LoadingComponent = Vue.extend(Loading)

    const toggleLoading = (el, binding) => {
      if (binding.value) {
        Vue.nextTick(() => {
          // 控制loading组件显示
          el.instance.visible = true
          // 插入到目标元素
          insertElement(el, el, binding)
        })
      } else {
        el.instance.visible = false
      }
    }

    const insertElement = (parent, el) => {
      // 给父元素加个定位，让loading元素定位
      el.style.position = 'relative';
      parent.appendChild(el.loadingComponent)
    }
    //添加指令
    Vue.directive('loading', {
      /**
       * 只调用一次，指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
       * @param {*} el 
       * @param {*} binding 
       * @param {*} vnode 
       */
      bind: function (el, binding, vnode) {
        const loadingComponent = new LoadingComponent({
          el: document.createElement('div'),
          data () { }
        })
        el.instance = loadingComponent
        el.loadingComponent = loadingComponent.$el
        el.loadingComponentStyle = {}
        binding.value && toggleLoading(el, binding)
      },
      update: function (el, binding) {
        if (binding.oldValue !== binding.value) {
          toggleLoading(el, binding)
        }
      },
      /**
       * 只调用一次，指令与元素解绑时调用。
       * @param {*} el 
       * @param {*} binding 
       */
      unbind: function (el, binding) {
        el.style.position = '';
        el.instance && el.instance.$destroy()
      }

    })
  }
}